# -*- coding: utf-8 -*-

# @File  : redis_util.py
# @Author: Lomo
# @Site  : lomo.space
# @Date  : 2020-02-11
# @Desc  : Redis


import redis

from config.db import REDIS_CONFIG


class RedisClient:
    def __init__(self, _type='LOCAL'):
        host = REDIS_CONFIG.get(_type).get('host')
        port = REDIS_CONFIG.get(_type).get('port')
        redis_pool = redis.ConnectionPool(host=host, port=port)
        self.r_client = redis.StrictRedis(connection_pool=redis_pool)

    def get_str(self, k):
        result = self.r_client.get(k)
        if result:
            return result.decode()

    def set_str(self, k, v, time=None):
        return self.r_client.set(k, v, time)

    def delete(self, k):
        flag = self.r_client.exists(k)
        if flag:
            return self.r_client.delete(k)
        else:
            return False

    def get_hash(self, name, k):
        """
        获取哈希表中的某个字段值
        :param name: 哈希表名
        :param k: key
        :return: dict
        """
        result = self.r_client.hget(name, k)
        dic = dict()
        if result:
            for k, v in result.items():
                dic[k.decode()] = v.decode()
        if dic:
            return dic
        else:
            return None

    def set_hash(self, name, k, v):
        """
        为哈希表赋值
        :param name: hash name
        :param k: key / filed name
        :param v: value
        :return:
        """
        return self.r_client.hset(name, k, v)

    def del_hash(self, name, k):
        """
        删除哈希表的某个字段
        :param name: 哈希表名
        :param k: key 字段名
        :return:
        """
        del_res = self.r_client.hdel(name, k)
        if del_res:
            return True
        else:
            print()
            return False

    def add_set(self, name, value):
        return self.r_client.sadd(name, value)

    def get_set_by_name(self, name):
        return self.r_client.smembers(name)

    def add_zset(self, k, dic):
        """
        向某个有序集合中添加数据
        :param k: key/name
        :param dic: dict
        :return: Boolean
        """
        return self.r_client.zadd(k, dic)

    def get_zset_len(self, k):
        """
        :param k: key
        :return: int
        """
        return self.r_client.zcard(k)
        pass
        # print(self.r_client.zrange(k, 0, count, desc=False, withscores=True))

    def get_zset_by_key(self, name, key):
        """
        获取有序集合中的某个值
        :param name: filed name
        :param key: key
        :return: float
        """
        return self.r_client.zscore(name, key)

    def is_expire(self, k):
        """
        判断某个 key 是否过期
        :param k:
        :return:
        """
        ttl = self.r_client.ttl(k)
        return ttl > 0

    def clean(self):
        """
        清空默认的 db(0)
        :return:
        """
        self.r_client.flushdb()

